package registration;

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
import javax.mail.PasswordAuthentication;
import javax.mail.Authenticator.*;
import OnlineExam.configuration.*;
import static OnlineExam.configuration.Configure.*;


/** 
 *  Handles sending a email required for user confirmation.
 */


public class MailConfirmation 
{
	    
	public long sendMail (String to)
	{
			
		long mailSentTime = System.currentTimeMillis ();  // calculates the current time.
	
		try 
		{
			Properties prop = System.getProperties ();
			
			prop.put ("mail.smtp.host", host);
			prop.put("mail.smtp.user", from);
   			prop.put("mail.smtp.port", port);
   			prop.put("mail.smtp.starttls.enable","true");
    		prop.put("mail.smtp.auth", "true");
    		prop.put("mail.smtp.socketFactory.port", port);
    		prop.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
  			prop.put("mail.smtp.socketFactory.fallback", "false");
	
			SecurityManager security = System.getSecurityManager();
	
			Authenticator auth = new SMTPAuthenticator();

			Session session = Session.getInstance (prop, auth);

			MimeMessage message = new MimeMessage (session);
		
			message.setFrom (new InternetAddress (from));

			message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

			message.setSubject("Webtests Confirmation Email.");

			message.setText("Please Click On the Link below to complete your Confirmation \n" + emailConfirmationAddress);

			Transport.send(message);   // sends the message.
			
			return mailSentTime;
		}
		catch (Exception e)
		{
			System.out.println ("Error in Sending mail " +e );
			return  mailSentTime;
		}
	}


	/**
	 *  Authentication of the username and password.
	 */

	
	private class SMTPAuthenticator extends javax.mail.Authenticator
    {
        public PasswordAuthentication getPasswordAuthentication()
        {
            return new PasswordAuthentication(from, emailPassword);
        }
    }
}
